﻿using System;
using System.Diagnostics;
using System.IO;
using CkSoftware.GroupMe.Sdk.Core.Dao;
using Newtonsoft.Json;

namespace CkSoftware.GroupMe.Sdk.Bot
{
	/// <summary>
	/// Handler for any bot callbacks.
	/// </summary>
	public class GroupMeBotCallbackHandler
	{
		/// <summary>
		/// Parses the supplied bot-callback content and returns a <see cref="GroupMeMessageData" /> object.
		/// </summary>
		/// <param name="callbackContent">The string content which was sent by the GroupMe callback call.</param>
		/// <exception cref="InvalidDataException">Occurs if the callbackContent is null or empty.</exception>
		/// <returns>The constructed <see cref="GroupMeMessageData" /> callback data.</returns>
		public GroupMeMessageData Parse(string callbackContent)
		{
			if (string.IsNullOrEmpty(callbackContent))
			{
				throw new InvalidDataException("The callback content cannot be empty.");
			}

			Trace.WriteLine("Trying to parse bot callback result '" + callbackContent + "'");

			var data = JsonConvert.DeserializeObject<GroupMeMessageData>(callbackContent);

			data.Received = DateTime.Now;
			data.RawData = callbackContent;

			return data;
		}
	}
}